package smecta.client.print.controller.product;

import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.control.Label;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.util.Callback;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import smecta.client.print.SpringbootJavafxApplication;
import smecta.client.print.util.AlertUtil;

import java.io.IOException;
import java.util.HashMap;

@Component
public class EntryController {
    private static final String SPECS_SETTING = "SPECS_SETTING";
    private static final String PRODUCT_SETTING = "PRODUCT_SETTING";
    private static final String PACKAGE_SETTING = "PACKAGE_SETTING";

    @Autowired
    private PropertyController propertyController;

    @Autowired
    private SpecsController specsController;

    @Autowired
    private ProductController productController;

    @Autowired
    private PackageController packageController;

    @FXML
    private TreeView<String> treeView;

    @FXML
    private StackPane contentPane;

    @FXML
    private BorderPane productPane;

    @FXML
    private String currentTreeNodeName;

    private static HashMap<String, String> nodeMapping = new HashMap<>();

    static {
        nodeMapping.put("类型设置", "leixing");
        nodeMapping.put("品名设置", "pinming");
        nodeMapping.put("分特数设置", "fenteshu");
        nodeMapping.put("F数设置", "fshu");
        nodeMapping.put("捻向设置", "nianxiang");
        nodeMapping.put("等级设置", "dengji");
        nodeMapping.put("色泽设置", "seze");
        nodeMapping.put("管色设置", "guanse");
        nodeMapping.put("筒重设置", "tongzhong");
        nodeMapping.put("箱重设置", "xiangzhong");
        nodeMapping.put("机台设置", "jitai");
        nodeMapping.put("包装班次设置", "baozhuangbanci");
        nodeMapping.put("执行标准设置", "zhixingbiaozhun");
    }

    @FXML
    private void initialize() {

        // 设置TreeView的选择模式，以便可以选中子节点
        treeView.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);

        // 为TreeView添加选择监听器
        treeView.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue != null) {
                handleTreeViewSelection(newValue);
            }
        });

        expandAll(treeView.getRoot());
    }

    private void expandAll(TreeItem<String> treeItem) {
        if (treeItem != null) {
            treeItem.setExpanded(true); // 展开当前节点
            for (TreeItem<String> child : treeItem.getChildren()) {
                expandAll(child); // 递归展开子节点
            }
        }
    }

    private void handleTreeViewSelection(TreeItem<String> selectedItem) {

        if (nodeMapping.containsKey(selectedItem.getValue())) {
            loadView("/fxml/product/PropertyListView.fxml");
            propertyController.manualInit(nodeMapping.get(selectedItem.getValue()));
            currentTreeNodeName = nodeMapping.get(selectedItem.getValue());
        }

        if ("规格设置".equals(selectedItem.getValue())) {
            loadView("/fxml/product/SpecsView.fxml");
            specsController.manualInit();
            currentTreeNodeName = SPECS_SETTING;
        }
        if ("商品设置".equals(selectedItem.getValue())) {
            loadView("/fxml/product/ProductListView.fxml");
            productController.manualInit();
            currentTreeNodeName = PRODUCT_SETTING;
        }
        if ("包装预置".equals(selectedItem.getValue())) {
            loadView("/fxml/product/PackageView.fxml");
            packageController.manualInit();
            currentTreeNodeName = PACKAGE_SETTING;
        }
    }

    private void loadView(String viewPath) {
        try {
            // 加载属性001列表查询界面的FXML
            FXMLLoader loader = new FXMLLoader(getClass().getResource(viewPath));
            loader.setControllerFactory(new Callback<Class<?>, Object>() {
                @Override
                public Object call(Class<?> param) {
                    // 控制器工厂提供bean注入，此处的缺点是不能根据bean名字注入，只能通过class类型注入bean
                    // 解决方案：
                    // 1、SpringbootJavafxApplication.applicationContext.getBean("Bean Name", Bean.class);
                    // 2、@Autowired private ApplicationContext applicationContext;
                    // Object bean_name = applicationContext.getBean("bean Name", Bean.class);
                    return SpringbootJavafxApplication.applicationContext.getBean(param);
                }
            });
            Parent listView = loader.load();
            contentPane.getChildren().clear();
            contentPane.getChildren().add(listView);
        } catch (IOException e) {
            e.printStackTrace();
            // 可以在这里显示错误信息
        }
    }

    private void showContentForSelection(TreeItem<String> selection) {
        // 根据选择的节点，动态加载不同的内容
        // 这里使用Label作为示例，实际应用中可以加载更复杂的布局
        contentPane.getChildren().clear();
        Label label = new Label("当前选择: " + selection.getValue());
        contentPane.getChildren().add(label);
    }

    @FXML
    private void handleAdd() {
        if (SPECS_SETTING.equals(currentTreeNodeName)) {
            specsController.add();
            return;
        }
        if (PRODUCT_SETTING.equals(currentTreeNodeName)) {
            productController.add();
            return;
        }
        if (PACKAGE_SETTING.equals(currentTreeNodeName)) {
            packageController.add();
            return;
        }
        propertyController.add(currentTreeNodeName);
    }

    @FXML
    private void handleDel() {
        if (SPECS_SETTING.equals(currentTreeNodeName)) {
            specsController.del();
            return;
        }
        if (PRODUCT_SETTING.equals(currentTreeNodeName)) {
            productController.del();
            return;
        }
        if (PACKAGE_SETTING.equals(currentTreeNodeName)) {
            packageController.del();
            return;
        }
        propertyController.del();
    }

    @FXML
    private void handleSave() {
        if (SPECS_SETTING.equals(currentTreeNodeName)) {
            specsController.save();
            AlertUtil.infoFinishAutoClose("保存成功", 2000L);
            return;
        }
        if (PRODUCT_SETTING.equals(currentTreeNodeName)) {
            productController.save();
            AlertUtil.infoFinishAutoClose("保存成功", 2000L);
            return;
        }
        if (PACKAGE_SETTING.equals(currentTreeNodeName)) {
            packageController.save();
            AlertUtil.infoFinishAutoClose("保存成功", 2000L);
            return;
        }
        // 保存操作
        propertyController.save(currentTreeNodeName);
        AlertUtil.infoFinishAutoClose("保存成功", 2000L);
    }

    @FXML
    private void handleClose() {
        // 关闭操作
        // 获取Stage实例
        Stage stage = (Stage) productPane.getScene().getWindow();
        // 关闭Stage
        stage.close();
    }
}